#pragma once
#include "ThreadCache.h"
#include "PageCache.h"
#include "PageMap.h"

static void* ConcurrentAlloc(size_t size) {
	if (size > MAX_BYTES) {
		size_t alignSize = SizeClass::RoundUp(size);
		size_t kpage = alignSize >> PAGE_SHIFT;

		PageCache::GetInstance()->mtx.lock();
		Span* span = PageCache::GetInstance()->NewSpan(kpage);
		span->_size = size;
		PageCache::GetInstance()->mtx.unlock();
		void* ptr = (void*)((PAGE_ID)span->_pageId << PAGE_SHIFT);
		return ptr;

	}
	else {


		if (TlsThreadCache == nullptr) {
			static ObjectPool< ThreadCache> object;
			TlsThreadCache = object.New();
			//TlsThreadCache = new ThreadCache();
		}

		//cout << std::this_thread::get_id() << ":" << TlsThreadCache << endl;
		return TlsThreadCache->Allocate(size);
	}


}


static void ConcurrentFree(void* ptr) {
	assert(ptr);
	//Span* span = PageCache::GetInstance()->MapObjectToSpan(ptr);
	//Span* span = (Span*) PageCache::GetInstance()->_pagemap.get((PAGE_ID)ptr >> PAGE_SHIFT);
	Span* span = (Span*)PageCache::GetInstance()->MapObjectToSpan((PAGE_ID)ptr >> PAGE_SHIFT);
	if (span->_size > MAX_BYTES) {
		
		PageCache::GetInstance()->mtx.lock();
		PageCache::GetInstance()->ReleaseSpanToPageCache(span);
		PageCache::GetInstance()->mtx.unlock();
	}
	else {
		TlsThreadCache->Deallocate(ptr, span->_size);

	}


}

